<script setup lang="ts">
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { regYuanToFen, timeFormat, timeStamp } from '@/hooks/util'
import cascader from '@/hooks/cascader.ts'
import * as accountApi from '@/api/account'
import * as fishApi from '@/api/fishGoods'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/store/modules/user'
import ImgView from './ImgView.vue'

import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
import 'dayjs/locale/zh-cn'

const themeStyle = {
  backgroundColor: localStorage.getItem('local_theme') || '#1890FF',
}
const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const imgViewRef = ref()

const myModal = ref()
const showModal = () => {
  myModal.value?.showModal()
}

defineExpose({
  showModal,
})

const emit = defineEmits<{
  refresh: []
}>()

let spinning = ref<boolean>(false)

const labelCol = {
  style: { width: '100px', textAlign: 'center' },
}
const wrapperCol = { span: 10 }

const formRef = ref()
interface formState {
  spBizType?: string
  categoryId?: string
  channelId?: string
  divisionId?: Array<string>
  robotId?: number
  images?: string
  sellingPrice?: number
  originalPrice?: number
  title?: string
  desc?: string
  inventory?: number
  transportFee?: number
  timePush?: any
}
const formState = ref<formState>({})

import type { RuleObject } from 'ant-design-vue/es/form/interface'
let validateChangeBalance = async (rule: RuleObject, value: string) => {
  value = String(value)
  if (value == null || value.trim() === '') {
    return Promise.reject('金额不能为空')
  }
  // 使用正则表达式来验证金额格式，允许整数和小数点后两位
  const regex = /^\d+(\.\d{1,2})?$/
  if (!regex.test(value)) {
    return Promise.reject('请输入有效的金额（整数或小数点后两位）')
  }
  // 将字符串转换为数字并检查是否大于0
  const amount = parseFloat(value)
  if (isNaN(amount) || amount <= 0) {
    return Promise.reject('请输入大于0的金额')
  }
  // 如果一切正常，返回成功
  return Promise.resolve()
}

import type { Rule } from 'ant-design-vue/es/form'
const rules: Record<string, Rule[]> = {
  spBizType: [{ required: true, message: '请选择行业名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择宝贝类目', trigger: 'blur' }],
  channelId: [{ required: true, message: '请选择宝贝渠道', trigger: 'blur' }],
  divisionId: [{ required: true, message: '请选择地区', trigger: 'blur' }],
  robotId: [{ required: true, message: '请选择店铺', trigger: 'blur' }],
  sellingPrice: [{ required: true, validator: validateChangeBalance, trigger: 'blur' }],
  originalPrice: [{ required: true, validator: validateChangeBalance, trigger: 'blur' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  desc: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  inventory: [{ required: true, message: '请输入库存', trigger: 'blur' }],
  transportFee: [{ required: true, message: '请输入邮费', trigger: 'blur' }],
}

import type { SelectProps } from 'ant-design-vue'

// 行业名称
let spBizType = ref<string>('')
const industryList = ref<SelectProps['options']>([])
const selectIndustry = (selectValue: any) => {
  spBizType.value = selectValue as string
  getCategoryList(spBizType.value)
}

// 宝贝类目
let categoryId = ref<string>('')
const categoryList = ref<SelectProps['options']>([])
const selectCategory = (selectValue: any) => {
  categoryId.value = selectValue as string
  getChannelList(categoryId.value)
}

// 宝贝渠道
const channelList = ref<SelectProps['options']>([])

// 地区
let cascaderValue = ref<string[]>([])
const cascaderChange = (value: any[], selectedOptions: any[]) => {
  cascaderValue.value = value
}
const filter = (inputValue: string, path: any[]) => {
  return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
}

const handleSubmit = async () => {
  formRef.value.validate().then(async () => {
    console.log('formState=', formState.value)

    const date = new Date(formState.value.timePush)
    const timestamp = date.getTime()
    console.log('timePush=', timestamp)

    let param = {
      spBizType: formState.value.spBizType,
      categoryId: formState.value.categoryId,
      channelId: formState.value.channelId,
      divisionId: formState.value.divisionId[formState.value.divisionId.length - 1],
      robotId: formState.value.robotId,
      sellingPrice: regYuanToFen(Number(formState.value.sellingPrice), 100),
      originalPrice: regYuanToFen(Number(formState.value.originalPrice), 100),
      title: formState.value.title,
      desc: formState.value.desc,
      inventory: formState.value.inventory,
      imgList: imgList.value,
      transportFee: regYuanToFen(formState.value.transportFee, 100),
      timerTime: timestamp,
    }
    spinning.value = true
    try {
      let { state, message: msg } = await fishApi.putawayTimerProduct(param)
      if (state === 200) {
        message.success('发布成功')
        myModal.value.cancelModal()
        setTimeout(() => {
          emit('refresh')
        }, 1000)
      } else {
        message.error(msg)
      }
    } catch (error) {
      message.error('网络请求连接失败~')
    }
    spinning.value = false
  })
}

// 获取行业
const getIndustryList = async () => {
  try {
    let { state, data, message: msg } = await fishApi.getSpBizType()
    if (state === 200) {
      industryList.value = data.map((item: any) => {
        return {
          label: item.name,
          value: item.number,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 获取类目
const getCategoryList = async (spBizTypeNum: string) => {
  try {
    let { state, data, message: msg } = await fishApi.getCategory({ spBizTypeNum })
    if (state === 200) {
      categoryList.value = data.map((item: any) => {
        return {
          label: item.name,
          value: item.number,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 获取渠道
const getChannelList = async (categoryNum: string) => {
  try {
    let { state, data, message: msg } = await fishApi.getChannel({ categoryNum })
    if (state === 200) {
      channelList.value = data.map((item: any) => {
        return {
          label: item.name,
          value: item.number,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 获取闲鱼店铺
const robatList = ref([])

const handleChangeRadio = (e: any) => {
  formState.value.robotId = e.target.value
}
const getRobatList = async () => {
  const params = { currentPage: 1, pageSize: 100 }
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotList(params)
    if (state === 200) {
      robatList.value = data.list.map((item: any) => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 宝贝图片
const imgList = ref<Array<string>>([])
interface FileItem {
  uid: string
  name?: string
  status?: string
}
const fileList = ref<FileItem[]>([])
const handleBeforeUpload = (file: any, fileList: any) => {
  return true
}

const customRequest = (option: any) => {
  const { onSuccess, onError, file, action, data = {} } = option
  const formData = new FormData()
  formData.append('file', file)
  formData.append('type', '1')
  fetch(action, {
    headers: {
      // 'User-Token': userStore.token,
      'User-Token': localStorage.getItem('token') as any,
    },
    method: 'POST',
    body: formData,
  })
    .then(response => response.json())
    .then(result => {
      onSuccess(result, file)
      if (result && result.data != null) {
        imgList.value.push(result.data)
      } else {
        message.error('图片太大，上传失败了!')
        fileList.value.pop()
      }
    })
    .catch(error => {
      message.error('图片太大，上传失败了')
      onError(error)
    })
}

// 预览图片
const handlePreview = async (file: any) => {
  if (file && file.response) {
    imgViewRef.value.showModal([file.response.data])
  } else {
    message.error('预览失败！')
  }
}

// 删除图片
const handleRemove = (file: any) => {
  if (file.status != 'error') {
    imgList.value = imgList.value.filter(item => item != file.response.data)
  }
}

interface FileInfo {
  file: FileItem
  fileList: FileItem[]
}
const handleChange = ({ fileList: newFileList }: FileInfo) => {
  fileList.value = newFileList.map((item: any) => {
    if (item.response && item.response.result == false) {
      return {
        uid: '-5',
        name: 'image.png',
        status: 'error',
      }
    } else {
      return item
    }
  })
}

let imgUploadUrl = ref('')
onMounted(() => {
  imgUploadUrl.value = `${localStorage.getItem('baseUrl')}/platform/wechatReply/uploadToAliOss`
  getIndustryList()
  getRobatList()
})
</script>

<template>
  <MyModal ref="myModal" title="定时发布宝贝" :width="900">
    <template #content>
      <a-alert
        description="提醒：由于当前商品发布功能正在调整更新，无法设置不同品类的的属性信息，推荐使用闲鱼app发布商品，发布后选择闲鱼账号，点击“同步当前闲鱼账号宝贝”"
        type="info"
        banner
        style="margin-bottom: 10px; padding: 10px"
      />

      <a-spin tip="Loading..." :spinning="spinning">
        <a-form
          style="height: 500px; overflow-y: scroll"
          ref="formRef"
          :rules="rules"
          :model="formState"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <div style="margin-bottom: 20px">
            <span class="titleFlag" :style="themeStyle"></span>
            <span class="title">基本信息</span>
          </div>

          <a-form-item label="行业名称" name="spBizType">
            <a-select
              v-model:value="formState.spBizType"
              @change="selectIndustry"
              placeholder="行业名称"
            >
              <a-select-option
                v-for="(item, index) in industryList"
                :key="index"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="宝贝类目" name="categoryId">
            <a-select
              v-model:value="formState.categoryId"
              @change="selectCategory"
              placeholder="宝贝类目"
            >
              <a-select-option
                v-for="(item, index) in categoryList"
                :key="index"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="宝贝渠道" name="channelId">
            <a-select v-model:value="formState.channelId" placeholder="宝贝渠道">
              <a-select-option
                v-for="(item, index) in channelList"
                :key="index"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="地区" name="divisionId">
            <a-cascader
              v-model:value="formState.divisionId"
              :options="cascader"
              :show-search="{ filter }"
              @change="cascaderChange"
              placeholder="地区"
            />
          </a-form-item>

          <div style="margin-bottom: 20px">
            <span class="titleFlag" :style="themeStyle"></span>
            <span class="title">发布的闲鱼店铺</span>
          </div>

          <a-form-item label="闲鱼店铺" name="robotId">
            <a-radio-group
              v-model:value="formState.robotId"
              :options="robatList"
              @change="handleChangeRadio"
              class="selectShop"
            />
          </a-form-item>

          <div style="margin-bottom: 20px">
            <span class="titleFlag" :style="themeStyle"></span>
            <span class="title">宝贝信息</span>
          </div>

          <!-- 
            action="http://ticket-expert-api.liangpiaovip.com/platform/wechatReply/uploadToAliOss"
            action="http://k8s-cluster.liangpiaovip.com:30080/ticket-expert/platform/wechatReply/uploadToAliOss"
          -->
          <a-form-item has-feedback name="images" label="宝贝图片">
            <a-upload
              :multiple="true"
              list-type="picture-card"
              :action="imgUploadUrl"
              :show-upload-list="{ showRemoveIcon: true }"
              :beforeUpload="handleBeforeUpload"
              :customRequest="customRequest"
              @preview="handlePreview"
              @remove="handleRemove"
              @change="handleChange"
              :file-list="fileList"
            >
              <upload-outlined></upload-outlined>
              上传图片
            </a-upload>
          </a-form-item>

          <a-form-item label="宝贝标题" name="title">
            <a-input v-model:value="formState.title"></a-input>
          </a-form-item>

          <a-form-item label="描述" name="desc">
            <a-textarea
              v-model:value="formState.desc"
              style="width: 500px; max-height: 260px"
              :maxlength="1000"
            ></a-textarea>
          </a-form-item>

          <a-form-item has-feedback label="售价" name="sellingPrice">
            <a-input-number
              v-model:value="formState.sellingPrice"
              style="width: 70%"
            ></a-input-number>
          </a-form-item>

          <a-form-item has-feedback label="原价" name="originalPrice">
            <a-input-number
              v-model:value="formState.originalPrice"
              style="width: 70%"
            ></a-input-number>
          </a-form-item>

          <a-form-item has-feedback label="库存" name="inventory">
            <template #help>如您店铺未开通鱼小铺，只能设置库存为1，否则会上品失败</template>
            <a-input-number v-model:value="formState.inventory" style="width: 70%"></a-input-number>
          </a-form-item>
          <a-form-item has-feedback label="邮费" name="transportFee">
            <a-input-number
              v-model:value="formState.transportFee"
              style="width: 70%"
            ></a-input-number>
          </a-form-item>

          <!-- 定时发布 -->
          <a-form-item has-feedback label="定时发布" name="timePush">
            <a-date-picker v-model:value="formState.timePush" showTime :locale="locale" />
          </a-form-item>
          <!-- 定时发布 -->
        </a-form>
        <div
          style="
            border-top: 1px solid #f0f0f0;
            text-align: right;
            padding-top: 10px;
            padding-right: 10px;
          "
        >
          <a-button @click="() => myModal.cancelModal()" style="margin-right: 10px">取消</a-button>
          <a-button type="primary" @click="handleSubmit">确定</a-button>
        </div>
      </a-spin>
    </template>
  </MyModal>
  <ImgView ref="imgViewRef"></ImgView>
</template>

<style scoped lang="less">
.titleFlag {
  display: inline-block;
  width: 4px;
  height: 16px;
  margin-right: 4px;
  // background-color: #7417be;
  border-radius: 2px;
}

.title {
  font-weight: bold;
  font-size: 16px;
}

.shop {
  display: inline-block;
  padding: 0 10px;
  height: 40px;
  line-height: 40px;
  border-radius: 20px;
  border: 1px solid #ebebeb;
  margin-right: 10px;
  margin-bottom: 5px;
}

/deep/ .ant-checkbox-group-item {
  padding: 0 10px;
  height: 40px;
  line-height: 40px;
  border-radius: 20px;
  border: 1px solid #ebebeb;
  margin-right: 10px;
  margin-bottom: 5px;
}

/deep/ .ant-checkbox-inner,
.ant-checkbox-input {
  border-radius: 50%;
}

/deep/ .ant-upload-list {
  width: 660px;
  font-feature-settings: 'tnum';
  box-sizing: border-box;
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
  font-variant: tabular-nums;
  line-height: 1.5715;
  list-style: none;
  margin: 0;
  padding: 0;
}
</style>
